<!--
 * @Description: 登录组件
 * @Author: zhihong deng
 * @Date: 2021-08-18 10:04:01
 * @LastEditors: zhihong deng
 * @LastEditTime: 2021-10-07 20:19:14
-->
<template>
  <div class="login-wrapper">
    <div class="modal">
      <el-form ref="userForm" :model="user" status-icon :rules="rules">
        <div class="title">火星</div>
        <el-form-item prop="userName">
          <el-input type="text" prefix-icon="el-icon-user" v-model="user.userName"/>
        </el-form-item>
        <el-form-item prop="userPwd">
          <el-input type="password" prefix-icon="el-icon-view" v-model="user.userPwd"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="btn-login" @click="login">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import storage from '../utils/storage'
import util from '../utils/utils'
export default {
  name:'login',
  data() {
    return {
      user: {
        userName: 'admin',
        userPwd: '123456'
      },
      rules: {
        userName: [
          {
            required: true,message: "请输入用户名",trigger: "blur"
          }
        ],
        userPwd: [
          {
            required: true,message: "请输入密码",trigger: "blur"
          }
        ]
      }
    }
  },
  mounted() {

  },
  methods: {
    login() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          // 调用login接口，传user对象过去
          this.$api.login(this.user)
          .then( async (res) => {
            console.log('res',res);
            this.$store.commit("saveUserInfo", res);
            await this.loadAsyncRoutes() // 登录成功后加载路由
            this.$router.push("/welcome");
          });
        } else {
          return false;
        }
      });
    },
    // 异步加载路由
    async loadAsyncRoutes () {
      let userInfo = storage.getItem('userInfo') || {}
      // 如果有token，就获取到权限列表
      if (userInfo.token) {
        try {
          const { menuList } = await this.$api.getPermissionList()
          let routes = util.generateRoute(menuList)
          // 遍历路由，批量添加路由
          routes.map( route => {
            let url = `../views/${route.component}.vue`
            route.component = () => import(url)
            this.router.addRoute("home", route) // 动态添加到home的子路由中
          })
        } catch (error) {
          
        }
      }
    }
  },
}
</script>

<style lang="scss">
  .login-wrapper{
    display: flex;
    justify-content: center;
    align-items: center;
    background: #f9fcff;
    width: 100vw;
    height: 100vh;
    .modal{
      width: 500px;
      padding: 50px;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 0 10px 3px #c7c9cb4d;
      .title{
        font-size: 50px;
        line-height: 1.5;
        text-align: center;
        margin-bottom: 30px;
      }
      .btn-login{
        width: 100%;
      }
    }
  }
</style>